package sample.cluster.simple

import akka.cluster.Cluster
import akka.cluster.ClusterEvent._
import akka.actor.ActorLogging
import akka.actor.Actor

class SimpleClusterListener extends Actor with ActorLogging {

  println("SimpleClusterListener ctor")
  val cluster = Cluster(context.system)

  // subscribe to cluster changes, re-subscribe when restart 
  override def preStart(): Unit = {
    println("preStart called, cluster subscribe MemberEvent")
    cluster.subscribe(self, initialStateMode = InitialStateAsEvents, //对大集群，mode=InitialStateAsSnapshot更好
      classOf[MemberEvent], classOf[UnreachableMember])
  }
  override def postStop(): Unit = cluster.unsubscribe(self) //unsubscribe all cluster domain events

  def receive = {
    //case state: CurrentClusterState =>
    //  log.info("cur members:{}",state.members.mkString(", "))
    case MemberUp(member) =>
      log.info("Member is Up: {}", member.address)
    case UnreachableMember(member) =>
      log.info("Member detected as unreachable: {}", member)
      Cluster(context.system).down(member.address) //实际中不应该手工下线，有可能是网络抖动。应通过jmx/rest使之下线
    case MemberRemoved(member, previousStatus) =>
      log.info("Member is Removed: {} after {}",
        member.address, previousStatus)
    case e: MemberEvent => // ignore
      log.info("other event: {}",e)
  }
}